package br.com.nirvana.loteria.input;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import br.com.nirvana.loteria.exception.UnzipException;

public class Unzip {

	public void unzipFile(File zipFile) throws UnzipException {

		try {
			InputStream in = new BufferedInputStream(new FileInputStream(
					zipFile));

			ZipInputStream zin = new ZipInputStream(in);

			ZipEntry e;

			while ((e = zin.getNextEntry()) != null) {
				unzipFile(zin, e.getName(), zipFile.getParent());
			}
			zin.close();
		} catch (IOException ex) {
			throw new UnzipException(ex);
		}
	}

	private void unzipFile(ZipInputStream zin, String entry, String folder) throws IOException {
		entry = entry.toLowerCase();

		System.out.println("unzipping " + entry);

		FileOutputStream out = new FileOutputStream(new File(folder, entry));
		byte[] b = new byte[512];
		int len = 0;
		while ((len = zin.read(b)) != -1) {
			out.write(b, 0, len);
		}
		out.close();
	}

}